package top.ply.manageservice.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.ply.common_unit.entity.RespEntity;
import top.ply.common_unit.global_resp.RespUtil;
import top.ply.manageservice.dao.RoleMapper;
import top.ply.manageservice.pojo.Manager;
import top.ply.manageservice.pojo.Role;
import top.ply.manageservice.service.ManagerService;
import top.ply.manageservice.service.impl.ManagerServiceImpl;

import javax.annotation.PostConstruct;
import java.util.*;

@RestController
@Validated
public class ManagerController {

    @Autowired
    ManagerServiceImpl managerService;

    @Autowired
    RoleMapper roleMapper;

    private Map<Integer, String> roles = new HashMap<>();

    private Set<Integer> roleSet = new HashSet<>();

    @PostConstruct
    private synchronized void init() {
        roles = roleMapper.getRoles();
        for (Map.Entry<Integer, String> entry : roles.entrySet()) {
            roleSet.add(entry.getKey());
        }
    }


    @PostMapping("/login")
    public RespEntity login(@RequestBody Map<String, String> data) {
        String username = data.get("username");
        String password = data.get("password");
        if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
            return managerService.login(username, password);
        } else {
            return RespUtil.illegalParameter();
        }
    }

    @PostMapping("/add")
    public RespEntity addManager(@RequestBody Manager manager, List<Integer> asRoles) {
        manager.setRoles(new ArrayList<>());
        for (Integer i : asRoles) {
            if (!roleSet.contains(i)) {
                return RespUtil.illegalParameter();
            } else {
                manager.getRoles().add(new Role(i, roles.get(i)));
            }
        }
        return managerService.addManager(manager);
    }



}
